<?php
namespace frontend\modules\v1\models;

use Yii;
use yii\base\Model;
use common\models\Business;
/**
 * Login form
 */
class LoginForm extends Model
{
    public $account;
    public $password;
    public $rememberMe = true;

    private $_business = false;


    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            // account and password are both required
            [['account', 'password'], 'required'],
            ['account', 'exist', 'targetClass' => '\common\models\Business', 'message' => '该手机号不存在.'],
            // rememberMe must be a boolean value
            ['rememberMe', 'boolean'],
            // password is validated by validatePassword()
            ['password', 'validatePassword'],
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validatePassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $business = $this->getBusiness();
            if (!$business || !$business->validatePassword($this->password)) {
                $this->addError($attribute, 'Incorrect account or password.');
            }
        }
    }

    /**
     * Logs in a user using the provided account and password.
     *
     * @return boolean whether the user is logged in successfully
     */
    public function login()
    {
        if ($this->validate()) {
            return Yii::$app->user->login($this->getBusiness(), $this->rememberMe ? 3600 * 24 * 30 : 0);
        } else {
            return false;
        }
    }

    /**
     * Finds business by [[account]]
     *
     * @return Business|null
     */
    public function getBusiness()
    {
        if ($this->_business === false) {
            $this->_business = Business::findByAccount($this->account);
        }
        return $this->_business;
    }
}
